package data_search

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic"
	"strconv"
)

// todo: 数据查找
func Search(c *gin.Context) {
	_, err := util.UserFilter(c)
	if err != nil {
		return
	}

	query := c.PostForm("query")
	if query == "" {
		util.FailedResponse(c, 10001, "输入不能为空")
		return
	}

	seedID, err := util.PostFormInt(c, "seed_id")
	if err != nil {
		return
	}
	limit, err := util.PostFormInt(c, "limit")
	if err != nil {
		return
	}
	offset, err := util.PostFormInt(c, "offset")
	if err != nil {
		return
	}

	var column models.Columns
	if err := db.DB.Where("seed_id = ?", seedID).Last(&column).Error; err != nil {
		util.FailedResponse(c, 10002, "未找到模板")
		return
	}
	fmt.Println(column.Headers)

	result, err := db.ElasticClient.Search("result_seed_" + strconv.Itoa(seedID)).
		//Type(strconv.Itoa(seedID)).
		Size(limit).From(offset).
		Query(elastic.NewQueryStringQuery(query)).Do(context.Background())
	if err != nil {
		util.FailedResponse(c, 10002, "查询出错")
		return
	}

	c.JSON(200, gin.H{
		"status":  10000,
		"message": "success",
		"columns": column.Value,
		"result":  result.Hits.Hits,
		"count":   result.TotalHits(),
	})

}
